package com.atguigu.flink.chapter11.function;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/9/25 10:36
 */
public class Flink01_Function_Scala {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        
        Table table = tenv.fromDataStream(waterSensorStream);
        
        // 1. 在table api中使用
        // 1.1 内联方式使用
        /*table
            .select($("id"), call(MyUpperCase.class, $("id").as("id_a")))
            .execute()
            .print();*/
        // 1.2 先注册函数, 然后再使用
        /*tenv.createTemporaryFunction("my_upper", MyUpperCase.class);
        table
            .select($("id"), call("my_upper", $("id")).as("id_a"))
            .execute()
            .print();*/
    
        // 2. 在sql中使用
        tenv.createTemporaryFunction("my_upper", MyUpperCase.class);
        tenv.sqlQuery("select id, my_upper(id) from " + table).execute().print();
        
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static class MyUpperCase extends ScalarFunction {
        public String eval(String s) {
            return s.toUpperCase();
        }
    }
}
/*
可以把小写字母转成大小

用法:
1. 在table api中使用


2. 在sql中使用
 */
